package com.xique.door.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xique.common.core.constant.OssFilePrefixConstants;
import com.xique.common.core.enums.StatusCode;
import com.xique.common.core.utils.AliossUtil;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Administrator
 * description:
 * path: platform-com.jzy.oms.api-AliossController
 * date: 2020/9/4 15:11
 */
@Controller
@RequestMapping("/alioss")
@Api("aliyunoss")
public class AliossController {

    @Autowired
    private AliossUtil aliossUtil;

    @Value("${alioss.jzy.endpoint}")
    private String endPoint;

    @Value("${alioss.jzy.accessKeyId}")
    private String accessKeyId;

    @Value("${alioss.jzy.accessKeySecret}")
    private String accessKeySecret;

    @Value("${alioss.jzy.bucketName}")
    private String parkBucketName;

    @Value("${alioss.park.filehost}")
    private String fileHost;

    /**
     * 根据文件名返回阿里oss文件第三方访问路径
     *
     * @param objectName 文件名（包含路径）
     * @return
     */
    @PostMapping("/getUrl")
    @ResponseBody
    public AjaxResult getAliossFileUrl(String objectName) {
        if (null != objectName && !"null".equals(objectName) && StringUtils.isNotEmpty(objectName)) {
            URL url = aliossUtil.getJzyGetObjectUrl(objectName);
            return AjaxResult.success("图片访问路径", url.toString());
        } else {
            return AjaxResult.success("无图片", "[表情]_pic.png");
        }

    }

    @ResponseBody
    @PostMapping("/uploadFile")
    @Log(title = "oss导入", businessType = BusinessType.IMPORT)
    @ApiOperation("oss文件导入")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false, defaultValue = OssFilePrefixConstants.FACE_URL) String fileType) {
        if (file != null) {
            Map<String, Object> resultMap = aliossUtil.uploadFile(file, fileType);
            if (resultMap.get("code").equals(StatusCode.ERROR.getCode())) {
                return AjaxResult.error("error", "文件上传失败！！！");
            }
            AjaxResult result = AjaxResult.success("success", "文件上传成功");
            result.put("url", resultMap.get("url"));
            result.put("objectName", resultMap.get("objectName"));

            return result;
        } else {
            return AjaxResult.error("error", "文件上传失败！！！");
        }
    }

    @ApiOperation(value = "文件下载")
    @GetMapping(value = "/download")
    @ResponseBody
    public AjaxResult download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {

        String status = aliossUtil.download(fileName, response);
        if (status.equals("error")) {
            return AjaxResult.error("error", "文件下载失败！！！");

        } else {
            return AjaxResult.error("success", "文件下载成功！！！");

        }
    }


    @ApiOperation(value = "文件删除")
    @GetMapping("/delete")
    @ResponseBody
    public AjaxResult DeleteFile(@RequestParam("fileName") String fileName) {

        String status = aliossUtil.delete(fileName);
        if (status.equals("error")) {
            return AjaxResult.error("error", "文件删除失败！！！");

        } else {
            return AjaxResult.success("success", "文件删除成功！！！");

        }
    }

    @ApiOperation(value = "generatePresignedUrl")
    @GetMapping("/test")
    @ResponseBody
    public AjaxResult testFile() {
        // 填写不包含Bucket名称在内的Object完整路径。
        String objectName = "test/2021/06/15/15a16881-17fe-4b2b-b955-6c9387cc25a8.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 60 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(parkBucketName, objectName, expiration);
        System.out.println("ossurl" + url);
        // 关闭OSSClient。
        ossClient.shutdown();
        return AjaxResult.success();

    }

    @ResponseBody
    @PostMapping("/uploadImage")
    @Log(title = "oss导入", businessType = BusinessType.IMPORT)
    @ApiOperation("oss文件导入")
    public AjaxResult reduceSizeAndUploadImage(@RequestParam("file") MultipartFile file) throws Exception {
        if (file != null) {
            Map<String, Object> resultMap = aliossUtil.reduceImageSizeAndUpload(file, 100);
            if (resultMap.get("code").equals(StatusCode.ERROR.getCode())) {
                return AjaxResult.error("error", "文件上传失败！！！");
            }
            AjaxResult result = AjaxResult.success("success", "文件上传成功");
            result.put("url", resultMap.get("url"));
            result.put("objectName", resultMap.get("objectName"));
            return result;
        } else {
            return AjaxResult.error("error", "文件上传失败！！！");
        }
    }
}